package com.mingweicai.intergration.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierTest {

  public static void main(String args[]){

    CyclicBarrier cyclicBarrier = new CyclicBarrier(3);

    WaitRunnable waitRunnable = new WaitRunnable(cyclicBarrier);

    Thread threadA = new Thread(waitRunnable);
    threadA.setName("A");
    threadA.start();

    Thread threadB = new Thread(waitRunnable);
    threadB.setName("B");
    threadB.start();

    Thread threadC = new Thread(waitRunnable);
    threadC.setName("C");
    threadC.start();

  }

  static class WaitRunnable implements Runnable{

    CyclicBarrier cyclicBarrier ;

    public WaitRunnable(CyclicBarrier cyclicBarrier){
      this.cyclicBarrier = cyclicBarrier;
    }

    @Override
    public void run() {
      try {
        System.out.println("Thread " + Thread.currentThread().getName() + " 第一次到达了栅栏");
        cyclicBarrier.await();

        System.out.println("Thread " + Thread.currentThread().getName() + " 第二次到达了栅栏");
        cyclicBarrier.await();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } catch (BrokenBarrierException e) {
        e.printStackTrace();
      }
    }
  }
}
